package cz.vutbr.fit.xzemko01.tfmcbs.validation.validators;

import java.util.Map;

import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.DiagnosticChain;

import cz.vutbr.fit.xzemko01.tfmcbs.model.Artifact;
import cz.vutbr.fit.xzemko01.tfmcbs.model.Entity;
import cz.vutbr.fit.xzemko01.tfmcbs.validation.utils.DiagnosticBuilder;

public class ArtifactValidator implements Validator<Artifact> {

	private static ArtifactValidator artifactValidator;
	
	private Validator<Entity> entityValidator;
	
	private ArtifactValidator() {
		entityValidator = EntityValidator.getInstance();
	}
	
	public static Validator<Artifact> getInstance() {
		if(artifactValidator == null) {
			artifactValidator = new ArtifactValidator();
		}
		
		return artifactValidator;
	}
	
	@Override
	public boolean validate(Artifact artifact, DiagnosticChain diagnostics, Map<Object, Object> context) {
		boolean result = entityValidator.validate(artifact, diagnostics, context);
		result &= validateArtifactStereotypeNotEmpty(artifact, diagnostics, context);
		result &= validateArtifactHasManifest(artifact, diagnostics, context);
		return result;
	}
	
	private boolean validateArtifactStereotypeNotEmpty(Artifact artifact, DiagnosticChain diagnostics, Map<Object, Object> context) {
		String stereoType = artifact.getStereotype();
		boolean result = true;

		if (stereoType == null || stereoType.trim().isEmpty()) {
			String errorMessage = "Artifact with name \"" + artifact.getName() + "\" stereotype is empty.";
			Diagnostic diagnostic = new DiagnosticBuilder(artifact)
											.setMessage(errorMessage).build();
			diagnostics.add(diagnostic);
			result = false;
		}
		return result;
	}
	
	private boolean validateArtifactHasManifest(Artifact artifact, DiagnosticChain diagnostics, Map<Object, Object> context) {
		boolean result = true;

		if (artifact.getManifestations() == null || artifact.getManifestations().isEmpty()) {
			String errorMessage = "Artifact with name \"" + artifact.getName() + "\" has not manifests any component.";
			Diagnostic diagnostic = new DiagnosticBuilder(artifact)
											.setSeverity(Diagnostic.WARNING)
											.setMessage(errorMessage).build();
			diagnostics.add(diagnostic);
			result = false;
		}
		return result;
	}
}
